package com.study.userserviceprovider.hystix;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import org.springframework.web.client.RestTemplate;

public class UserHsytixCommand extends HystrixCommand<String> {
    int num;

    RestTemplate restTemplate;

    public UserHsytixCommand(int num, RestTemplate restTemplate) {
        super(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("spring-cloud-order-service"))
            .andCommandPropertiesDefaults(
                    HystrixCommandProperties.Setter().withCircuitBreakerEnabled(true)
                    .withCircuitBreakerRequestVolumeThreshold(5)
            )
        );
        this.num = num;
        this.restTemplate = restTemplate;
    }


    public UserHsytixCommand(HystrixCommandGroupKey groupKey) {
        super(groupKey);
    }

    @Override
    protected String run() throws Exception {
        if(num%2 == 0){
            return "正常访问";
        }
        return  restTemplate.getForObject("http://spring-cloud-order-service/orders",String.class);
    }

    @Override
    protected String getFallback() {
        return "请求被降级";
    }
}
